WordPress利用jQuery实现向上向下滑动

对浏览长文章读者而言,有返回顶部、下到底部和移动到评论框这几个快捷键是非常人性化的。而且那种滑动比一下子就到顶的方式要显得更为酷炫。找了好久,终于在网上找到了一个完美的教程。
本文参考:http://blog.ifenwen.com/wordpress-uses-jquery-getting-upward-and-downward-slide/

与 http://www.shangk.org/archives/40.html整合而来

下面我们就开始添加代码:(代码看懂前提需掌握Html、Css、JavaScript、Php、jQuery)

1、在主题文件footer.php中添加如下代码:

<!-- shangxia START -->
<div id="shangxia"><div id="shang"></div><div id="comt"></div><div id="xia"></div></div>
<!-- shangxia END -->

注意要加在body结束标签之前。

2、在主题文件header.php的head区域添加如下代码:

<!-- shangxia START -->
<?php if (is_single()) { ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/shangxia-single.css" type="text/css" />
<?php } else { ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/shangxia-other.css" type="text/css" />
<?php } ?>
<script type="text/javascript">
<!--
jQuery(document).ready(function($){
var s= $('#shangxia').offset().top;$(window).scroll(function (){$("#shangxia").animate({top : $(window).scrollTop() + s + "px" },{queue:false,duration:500});});
$body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
$('#shang').click(function(){$body.animate({scrollTop: '0px'}, 400);});
$('#xia').click(function(){$body.animate({scrollTop:$('#footer').offset().top}, 800);});
$('#comt').click(function(){$body.animate({scrollTop:$('#comments').offset().top}, 800);});
});
-->
</script>

说明:这步通过条件语句判断加载不同的CSS文件,然后是调用了jQuery类库,并添加效果代码。

3、在主题目录中创建shangxia-single.css文件,内容为:

/* shangxia-single START */
#shangxia{position:absolute;top:40%;left:50%;margin-left:338px;display:block;}
#shang{background:url(images/shangxia.gif) no-repeat;position:relative;cursor:pointer;height:42px;width:32px;margin:10px 0;}
#comt{background:url(images/shangxia.gif) no-repeat center -45px;position:relative;cursor:pointer;height:32px;width:32px;margin:10px 0;}
#xia{background:url(images/shangxia.gif) no-repeat center -78px;position:relative;cursor:pointer;height:42px;width:32px;margin:10px 0;}
/* shangxia-single END */

4、在主题目录中创建shangxia-other.css文件,内容为:

/* shangxia-other START */
#shangxia{position:absolute;top:40%;left:50%;margin-left:338px;display:block;}
#shang{background:url(images/shangxia.gif) no-repeat;position:relative;cursor:pointer;height:42px;width:32px;margin:10px 0;}
#xia{background:url(images/shangxia.gif) no-repeat center -78px;position:relative;cursor:pointer;height:42px;width:32px;margin:10px 0;}
/* shangxia-other END */

5、准备好图片素材,到主题的img目录中:

shangxia_pic_2

这个文件尺寸为32×119,其必须和第3、4步的css代码相配合才行。

3 条评论

  1. 番茄说道:

    这个效果不错,我去折腾一下。不过有一点就是,如何调整这个小工具在网页左右两边的距离?

  2. 分文网说道:

    呵呵 欢迎转载。。。

留下只言片语: